package com.iuweb.login.controller;


import com.iuweb.commen.cst.Const;
import com.iuweb.login.model.User;
import com.iuweb.login.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ruiwu
 * @version V1.0
 * @Description:用户Controller层
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    private final static Logger log = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private LoginService loginService;

    @RequestMapping("/doLogin")
    public String login(User user, Model model){
        Subject subject = SecurityUtils.getSubject() ;
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassword()) ;
        try{
            //.login(token)来通过shiro进行认证
            subject.login(token);
            Session session=subject.getSession();
            user = loginService.findUserByUsername(user.getUserName());
            session.setAttribute("LoginUser", user);
            log.info("登录成功，账号为"+user.getUserName()+"；密码为"+user.getPassword());
            return "redirect:"+ Const.HOME_URL;
        }catch(Exception e){
            //验证失败
            log.info("没有找到该账号");
            e.printStackTrace();
            return "/index";
        }
    }
    /**
     * @Description:退出登录
     * @param @param user
     * @param @param request
     * @param @return
     * @author daisc
     * @date 2018年1月4日 下午2:27:53
     * @version V1.0
     */
    @RequestMapping("/logout")
    public String logout(User user, HttpServletRequest request){
        try{
            Subject subject = SecurityUtils.getSubject();
            if (subject.isAuthenticated()) {
                subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
            }
            log.info("账号为"+user.getUserName()+"；密码为"+user.getPassword()+"退出登录成功");
            return "redirect:/login.jsp";
        }catch(Exception e){
            //验证失败
            log.info("退出登录失败");
            e.printStackTrace();
            return "/index";
        }
    }
  }
